package com.jbookshelf.dal.providers;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jbookshelf.dal.entities.Users;

@Repository
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public class UsersDataProviderImp implements UsersDataProvider {

	@Autowired
	SessionFactory sessionFactory;

	@Override
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	@SuppressWarnings("unchecked")
	public List<Users> getUsers() {
		Session s = sessionFactory.getCurrentSession();
		Query q = s.createQuery("from Users u");
		return q.list();
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public Users getUserByLogin(String login) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from Users where login=:login");
		query.setString("login", login);
		return (Users) query.uniqueResult();
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public Users getUserByEmail(String email) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from Users where email=:email");
		query.setString("email", email);
		return (Users) query.uniqueResult();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveUser(Users user) {
		Session s = sessionFactory.getCurrentSession();
		s.save(user);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateUser(Users user) {
		Session s = sessionFactory.getCurrentSession();
		s.update(user);

	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public Users getUserById(int id) {
		Session session = sessionFactory.getCurrentSession();
		return (Users) session.get(Users.class, id);
	}

}
